package com.loe.mvp.util

import com.loe.mvp.ext_java.boolean
import com.loe.mvp.ext_java.double
import com.loe.mvp.ext_java.int
import com.loe.mvp.ext_java.long
import org.json.JSONObject
import java.io.Serializable
import java.net.URLDecoder

/**
 * Url参数解析
 *
 * @author 章路顺
 * @since 2022/7/10-9:45
 */
class SUrl(s: String) : Serializable
{
    val scheme: String

    val path: String

    var query: String = ""
        private set

    val paramMap = HashMap<String, String>()

    init
    {
        val sp = URLDecoder.decode(s, "UTF-8").split("?")
        val ss = sp[0].split("://")

        if (ss.size > 1)
        {
            scheme = ss[0]
            path = ss[1]
        } else
        {
            scheme = ""
            path = ss[0]
        }

        if (sp.size > 1)
        {
            query = sp[1]
            val params = query.split("&")
            params.forEach()
            {
                val kv = it.split("=")
                if (kv.size > 1)
                {
                    paramMap[kv[0]] = URLDecoder.decode(kv[1], "UTF-8")
                } else
                {
                    paramMap[kv[0]] = ""
                }
            }
        }
    }

    operator fun get(key: String): String
    {
        return paramMap[key] ?: ""
    }

    fun getInt(key: String): Int
    {
        return paramMap[key].int
    }

    fun getBoolean(key: String): Boolean
    {
        return paramMap[key].boolean
    }

    fun getDouble(key: String): Double
    {
        return paramMap[key].double
    }

    fun getLong(key: String): Long
    {
        return paramMap[key].long
    }

    fun paramJson(): JSONObject
    {
        val params = JSONObject()
        paramMap.forEach()
        {
            params.put(it.key, it.value)
        }
        return params
    }

    fun paramString(): String
    {
        return paramJson().toString()
    }
}